package com.example.mr5.money.main;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.example.mr5.money.constant.Constant;
import com.example.mr5.money.main.calculator.Calculator;
import com.example.mr5.money.main.express.ExpressActivity;
import com.example.mr5.money.main.home.HomeFragment;
import com.example.mr5.money.main.myexpense.addexpense.AddMyExpenseActivity;
import com.example.mr5.money.main.myincome.addincome.AddMyIncomeActivity;
import com.example.mr5.money.main.myincome.MyIncomeFragment;
import com.example.mr5.money.R;
import com.example.mr5.money.main.myexpense.MyExpenseFragment;
import com.example.mr5.money.main.userdefined.UserDefinedFragment;

import java.util.ArrayList;
import java.util.List;

import static com.example.mr5.money.R.id.fragment_content;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener, View.OnClickListener {

    private static final int FRAGMENT_HOME = 0;
    private static final int FRAGMENT_MY_INCOME = 1;
    private static final int FRAGMENT_MY_EXPENSE = 2;
    private static final int FRAGMENT_USER_DEFINED = 3;

    private DrawerLayout drawer;
    private Toolbar toolbar;
    private FrameLayout fragmentContent;
    private List<Fragment> fragments;
    private HomeFragment homeFragment;
    private MyIncomeFragment myIncomeFragment;
    private MyExpenseFragment myExpenseFragment;
    private UserDefinedFragment userDefinedFragment;
    private int currentFragment = 0;

    private MenuItem filterItem;
    private PopupWindow popupWindow;
    private FloatingActionButton fab;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        initView();
        initFragment();
    }

    private void initView() {
        fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(this);

        drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        navigationView.setCheckedItem(R.id.nav_home);//default fragment

    }

    private void initFragment() {
        fragments = new ArrayList<>();
        homeFragment = new HomeFragment();
        myIncomeFragment = new MyIncomeFragment();
        myExpenseFragment = new MyExpenseFragment();
        userDefinedFragment = new UserDefinedFragment();
        fragments.add(homeFragment);
        fragments.add(myIncomeFragment);
        fragments.add(myExpenseFragment);
        fragments.add(userDefinedFragment);

        fragmentContent = (FrameLayout) findViewById(fragment_content);
        FragmentTransaction ft = this.getSupportFragmentManager().beginTransaction();
        ft.add(R.id.fragment_content, homeFragment);
        ft.commit();
    }

    private void setFragmentAttr(int index) {
        switch (index) {
            case FRAGMENT_HOME:
                setTitle("Money");
                fab.setVisibility(View.VISIBLE);
                filterItem.setVisible(false);
                break;
            case FRAGMENT_MY_INCOME:
                setTitle("我的收入");
                fab.setVisibility(View.VISIBLE);
                filterItem.setVisible(true);
                filterItem.setTitle("刷选");
                break;
            case FRAGMENT_MY_EXPENSE:
                setTitle("我的支出");
                fab.setVisibility(View.VISIBLE);
                filterItem.setVisible(true);
                filterItem.setTitle("刷选");
                break;
            case FRAGMENT_USER_DEFINED:
                setTitle("自定义收支");
                fab.setVisibility(View.INVISIBLE);
                filterItem.setVisible(true);
                filterItem.setTitle("编辑");
                if (userDefinedFragment.getAdapter() != null) {
                    userDefinedFragment.getAdapter().setEditable(false);
                    userDefinedFragment.getAdapter().notifyDataSetChanged();
                    userDefinedFragment.setEditable(false);
                }
                break;
        }
    }


    private long firstPressedTime = 0;

    @Override
    public void onBackPressed() {
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            if (firstPressedTime == 0) {
                firstPressedTime = System.currentTimeMillis();
                Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_LONG).show();
            } else {
                if (System.currentTimeMillis() - firstPressedTime < 1000) {
                    finish();
                    System.exit(0);
                } else {
                    firstPressedTime = 0;
                }
            }


        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        filterItem = menu.findItem(R.id.action_filter);
        filterItem.setVisible(false);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_filter) {
            if (currentFragment == FRAGMENT_USER_DEFINED) {
                if (userDefinedFragment.getAdapter().getEditable()) {
                    filterItem.setTitle("编辑");
                    //save data to db
                } else {
                    filterItem.setTitle("保存");
                }
                userDefinedFragment.getAdapter().setEditable(!userDefinedFragment.getAdapter().getEditable());
                userDefinedFragment.getAdapter().notifyDataSetChanged();
                userDefinedFragment.setEditable(userDefinedFragment.getAdapter().getEditable());

            } else if (currentFragment == FRAGMENT_MY_INCOME) {
                myIncomeFragment.showPopupWindow(toolbar);
            } else if (currentFragment == FRAGMENT_MY_EXPENSE) {
                myExpenseFragment.showPopupWindow(toolbar);
            }
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_home) {
            changeFragment(Constant.FLAG_HOME_FRAGMENT);
            setFragmentAttr(Constant.FLAG_HOME_FRAGMENT);

        } else if (id == R.id.nav_income) {
            changeFragment(Constant.FLAG_MYINCOME_FRAGMENT);
            setFragmentAttr(Constant.FLAG_MYINCOME_FRAGMENT);

        } else if (id == R.id.nav_expense) {
            changeFragment(Constant.FLAG_MYEXPENSE);
            setFragmentAttr(Constant.FLAG_MYEXPENSE);

        } else if (id == R.id.nav_user_defined) {
            changeFragment(Constant.FLAG_USER_DEFINED);
            setFragmentAttr(Constant.FLAG_USER_DEFINED);
        } else if (id == R.id.nav_express) {
            Intent intent = new Intent(this, ExpressActivity.class);
            startActivity(intent);
        } else if (id == R.id.nav_calculate) {
            Intent intent = new Intent(this, Calculator.class);
            startActivity(intent);
        }

        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    private void changeFragment(int id) {
        Fragment fragment = fragments.get(id);
        FragmentTransaction ft = this.getSupportFragmentManager().beginTransaction();
        fragments.get(currentFragment).onPause(); // pause current fragment
        if (fragment.isAdded()) {
            fragment.onResume(); // resume next fragment
        } else {
            ft.add(R.id.fragment_content, fragment);
        }
        for (int i = 0; i < fragments.size(); i++) {
            fragment = fragments.get(i);
            if (id == i) {
                ft.show(fragment);
            } else {
                ft.hide(fragment);
            }
        }
        currentFragment = id;
        ft.commit();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.fab:
                if (currentFragment == FRAGMENT_HOME) {
                    showPopupWindow();
                } else if (currentFragment == FRAGMENT_MY_INCOME) {
                    startActivity(new Intent(MainActivity.this, AddMyIncomeActivity.class));

                } else if (currentFragment == FRAGMENT_MY_EXPENSE) {
                    startActivity(new Intent(MainActivity.this, AddMyExpenseActivity.class));

                } else if (currentFragment == FRAGMENT_USER_DEFINED) {

                }

                break;
            case R.id.add_income_text:
                startActivity(new Intent(MainActivity.this, AddMyIncomeActivity.class));
                popupWindow.dismiss();
                break;
            case R.id.add_expense_text:
                startActivity(new Intent(MainActivity.this, AddMyExpenseActivity.class));
                popupWindow.dismiss();
                break;
            case R.id.add_user_defined_text:
                popupWindow.dismiss();
                break;
        }
    }

    private void showPopupWindow() {
        backgroundAlpha(0.5f);//让背景变暗
        View popupWindow_view = getLayoutInflater().inflate(R.layout.popupwindow_add_record, null, false);
        TextView addIncomeText = (TextView) popupWindow_view.findViewById(R.id.add_income_text);
        TextView addExpenseText = (TextView) popupWindow_view.findViewById(R.id.add_expense_text);
        TextView addUserDefinedText = (TextView) popupWindow_view.findViewById(R.id.add_user_defined_text);
        addIncomeText.setOnClickListener(this);
        addExpenseText.setOnClickListener(this);
        addUserDefinedText.setOnClickListener(this);
        popupWindow = new PopupWindow(popupWindow_view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setAnimationStyle(R.style.popWindowAnimation);//设置弹出和消失的动画
        popupWindow.setFocusable(true);// 取得焦点
        popupWindow.setOutsideTouchable(true);
        popupWindow.setTouchable(true);
        popupWindow.showAtLocation(popupWindow_view, Gravity.BOTTOM, 0, 0);
        // 点击窗体内其他地方消失
        popupWindow_view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // TODO Auto-generated method stub
                if (popupWindow != null && popupWindow.isShowing()) {
                    backgroundAlpha(1);
                    popupWindow.dismiss();
                    popupWindow = null;
                }
                return false;
            }
        });

        //设置消失的监听
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1);
            }
        });
    }

    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getWindow().setAttributes(lp);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {

    }
}
